package com.wwx.util;

import java.io.IOException;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * 字符转码过滤器
 * @author THTF
 *
 */
public class CharacterEncodingFilter implements Filter{

	private String oldEncoding;
	private String newEncoding;
	public void destroy() {
	}
	public void doFilter(ServletRequest arg0, ServletResponse arg1,
			FilterChain arg2) throws IOException, ServletException {
		HttpServletRequest request=(HttpServletRequest)arg0;
		HttpServletResponse response=(HttpServletResponse)arg1;
		
		String method=request.getMethod();
		if("get".equalsIgnoreCase(method)){
			Map<String, String[]> map =request.getParameterMap();
			Collection<String[]> values=map.values();
			Iterator<String[]> it =values.iterator();
			while(it.hasNext()){
				String[] str = it.next();
				for (int i = 0; i < str.length; i++) {
					str[i] = new String(str[i].getBytes(oldEncoding),newEncoding);
				}
			}
		}else{
			request.setCharacterEncoding(newEncoding);
		}
		response.setCharacterEncoding(newEncoding);
		arg2.doFilter(request, response);
	}

	public void init(FilterConfig arg0) throws ServletException {
		oldEncoding=arg0.getInitParameter("oldEncoding");
		newEncoding=arg0.getInitParameter("newEncoding");
	}
	
}
